﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ArbolandiaBL;
using System.Text;
public partial class _Categories : System.Web.UI.Page
{
    String category = "";
    String searchC = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        string pn = Request.QueryString["pn"]; pn = string.IsNullOrEmpty(pn) ? "0" : pn;
        int res;
        category = Request.QueryString["c"]; category = string.IsNullOrEmpty(category) ? "" : category;
        if (!Int32.TryParse(category, out res)) { category = ""; }
        searchC = Request.QueryString["sc"]; searchC = string.IsNullOrEmpty(searchC) ? "" : searchC;
        //btnHiddenSearch.Click += new EventHandler(checked_Change);
        //btnUpdateSearch.OnClientClick = "fnGetFilters();";
        //Pintamos los controles de busqueda avanzada
        LoadBanners();
        lblRoute.Text = "INICIO"; lblRoute.NavigateUrl = "Default.aspx";
        lblRoute1.Text = " / BÚSQUEDA";
        PrintAdvancedControls();
        if (!IsPostBack)
        {
            //Path

        }
        ApplyFilters(searchC, pn, category, "", "", 0, 0, "", "");
    }
    protected void ApplyFilters(string searchC, string pn, string category, string subcategory, string colors, decimal pricemin, decimal pricemax, string meses, string altura)
    {
        productslist.Controls.Clear();
        //Get Order by
        int orderby = 0; // 0 ningun 1 A-Z , 2 Z-A  , 3 Menor - mayor , 4 mayor - menor
        Int32.TryParse(drpOrderBy.SelectedValue, out orderby);

        var service = new ServiceUI();
        //obtenemos los criterios de busqueda.
        int ipn = 0;
        Int32.TryParse(pn, out ipn);
        //Primera busqueda cuando viene de cualquier otra pagina
        var tmpproducts = new ServiceUI().GetAdvancedSearch(searchC, pricemin, pricemax, category, subcategory, meses, colors, altura, "");
        var orderedList = new List<UIProductResume>();
        if (orderby == 1) { orderedList = tmpproducts.OrderBy(w => w.Name).ToList(); }
        else if (orderby == 2) { orderedList = tmpproducts.OrderByDescending(w => w.Name).ToList(); }
        else if (orderby == 3) { orderedList = tmpproducts.OrderBy(w => w.LowerPrice).ToList(); }
        else if (orderby == 4) { orderedList = tmpproducts.OrderByDescending(w => w.LowerPrice).ToList(); }
        else { orderedList = tmpproducts; }

        var products = orderedList.Skip((ipn - 1) * 5).Take(5).ToList();

        //Llenamos el paginador
        if (tmpproducts.Count() > 5)
        {
            FillPaginator(tmpproducts.Count(), Int32.Parse(pn));
        }

        //add products
        for (int i = 0; i < products.Count(); i++)
        {
            var div = new HtmlGenericControl("div");
            div.Attributes.Add("class", "product");
            div.Attributes.Add("style", "cursor:pointer;");
            div.Attributes.Add("onclick", "document.location.href='Detail.aspx?d=" + products[i].Id + "'");

            //Image
            var divImg = new HtmlGenericControl("div");
            divImg.Attributes.Add("class", "product-img");
            var img = new Image();
            img.Width = Unit.Percentage(100);
            img.Height = Unit.Percentage(100);
            img.ImageUrl = products[i].ImageUrl;
            divImg.Controls.Add(img);

            //Middle
            var divMiddle = new HtmlGenericControl("div");
            divMiddle.Attributes.Add("class", "product-middle");
            var divMiddleText = new HtmlGenericControl("div");
            divMiddleText.Attributes.Add("class", "product-middle-name");
            divMiddleText.InnerText = products[i].Name;
            divMiddle.Controls.Add(divMiddleText);
            var divMiddleInfo = new HtmlGenericControl("div");
            divMiddleInfo.Attributes.Add("class", "product-middle-info");
            divMiddleInfo.InnerText = products[i].ShortDescription;
            divMiddle.Controls.Add(divMiddleInfo);
            var divMiddlePrice = new HtmlGenericControl("div");
            divMiddlePrice.Attributes.Add("class", "product-middle-price");
            divMiddlePrice.InnerText = "Desde " + products[i].LowerPrice.ToString("C") + " pesos";
            divMiddle.Controls.Add(divMiddlePrice);

            //Prefencias
            var divPrefs = new HtmlGenericControl("div");

            divPrefs.Attributes.Add("class", "product-preferencias");
            var prefsTitle = new HtmlGenericControl("span");
            prefsTitle.Attributes.Add("class", "product-preferencias-title");
            prefsTitle.InnerText = "Preferencias";
            divPrefs.Controls.Add(prefsTitle);
            int max = 6;

            for (int j = 0; j < products[i].ProductPreferences.Count; j++)
            {
                if (j >= max) { break; }
                var prefImg = new Image();
                prefImg.CssClass = "product-preferencias-imgs-" + ((j == 0 || j == 2 || j == 4) ? "left" : "right");
                prefImg.ImageUrl = products[i].ProductPreferences[j].ImageUrl;
                divPrefs.Controls.Add(prefImg);
            }

            div.Controls.Add(divImg);
            div.Controls.Add(divMiddle);
            div.Controls.Add(divPrefs);
            productslist.Controls.Add(div);
        }
    }
    protected void FillPaginator(Int32 total, int pn)
    {
        string c = "";
        //Paginator
        Int32 totalPages = total / 10;
        Int32 residuo = total % 10;
        if (totalPages == 0)
        {
            totalPages = 1;
        }
        else if (residuo > 0)
        {
            totalPages += 1;
        }
        if (pn == 0) { pn = 1; }
        //Add anterior
        if (pn > 1)
        {
            var pageanterior = new Label();
            pageanterior.Text = "« Anterior";
            pageanterior.Attributes.Add("style", "padding-left:10px; padding-right:10px;");
            pageanterior.Attributes.Add("onclick", "document.location.href='AdvancedSearch.aspx?pn=" + (pn - 1).ToString() + (!string.IsNullOrEmpty(c) ? "&cat=" + c : "") + "';");
            paginator.Controls.Add(pageanterior);
        }

        //Add numbers
        for (int i = 1; i <= totalPages; i++)
        {
            var page = new HtmlGenericControl("span");
            page.InnerText = i.ToString();
            if (pn.ToString() == i.ToString())
            {
                page.Attributes.Add("style", "background-color: #edeff4; color: gray; border: solid 1px gray;");
            }
            page.Attributes.Add("onclick", "document.location.href='AdvancedSearch.aspx?pn=" + i.ToString() + (!string.IsNullOrEmpty(c) ? "&cat=" + c : "") + "';");
            paginator.Controls.Add(page);
        }

        //Add siguiente
        var pagesiguiente = new HtmlGenericControl("span");
        pagesiguiente.InnerText = "Siguiente »";
        pagesiguiente.Attributes.Add("style", "padding-left:10px; padding-right:10px;");
        var tempnext = pn + 1;
        if (tempnext > totalPages)
        {
            tempnext = totalPages;
        }
        pagesiguiente.Attributes.Add("onclick", "document.location.href='AdvancedSearch.aspx?pn=" + tempnext.ToString() + (!string.IsNullOrEmpty(c) ? "&cat=" + c : "") + "';");
        paginator.Controls.Add(pagesiguiente);

        var br = new HtmlGenericControl("br");
        paginator.Controls.Add(br);

        //End of paginator
    }
    protected void PrintAdvancedControls()
    {
        //Obtenemos las categorias seleccionadas para saber cuales sub-categorias se muestran.

        if (categorysSelected.Value.Length > 0)
        {
            //obtenemos categorias
            var listCat = GetIds(categorysSelected.Value.Replace("chk_category_", ""), '|');
            //Llenamos subcategorias
            var subcat = new Service().GetSubcategorys();
            var tmpSubCat = from p in subcat
                            join w in listCat on p.Product_CategoryId equals w
                            select p;
            for (int i = 0; i < tmpSubCat.Count(); i++)
            {
                if (i > 0) { divLeftSubcategorias.Controls.Add(new LiteralControl("<br/>")); }
                CheckBox chk = new CheckBox()
                {
                    ID = "chk_subcategory" + subcat[i].Id,
                    Text = subcat[i].Name,
                    ClientIDMode = System.Web.UI.ClientIDMode.Static
                };
                //chk.CheckedChanged += new EventHandler(checked_Change);
                //chk.AutoPostBack = true;
                chk.Attributes.Add("onclick", "fnFillAllSelected('#divLeftSubcategorias','#subCategorysSelected')");
                divLeftSubcategorias.Controls.Add(chk);
            }
        }

        //llenamos Colores
        var colors = new Service().GetColors();
        for (int i = 0; i < colors.Count(); i++)
        {
            //var color = new HtmlGenericControl("input");
            var color = new HtmlInputCheckBox();
            color.ID = "chk_color_" + colors[i].Id;
            color.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            var label = new HtmlGenericControl("label");
            label.Attributes.Add("for", color.ID);
            label.Style.Add("background-color", colors[i].HexColor);
            label.Style.Add("background-image", "none");
            label.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            divLeftColor.Controls.Add(color);
            divLeftColor.Controls.Add(label);
        }


    }
    protected List<Int32> GetIds(string chain, char separator)
    {
        var res = new List<Int32>();
        var listString = chain.Split(separator);
        Int32 resi;
        foreach (var item in listString)
        {
            if (Int32.TryParse(item, out resi))
            {
                res.Add(resi);
            }
        }
        return res;

    }
    protected void checked_Change(object sender, EventArgs e)
    {
        decimal minp, maxp;
        Decimal.TryParse(minprice.Value, out minp); Decimal.TryParse(maxprice.Value, out maxp);
        var allcategorys = categorysSelected.Value.Replace("chk_category_", "");
        var allsubCategorys = subCategorysSelected.Value.Replace("chk_subcategory", "");
        var allcolors = colorsSelected.Value.Replace("chk_color_", "");
        var allMeses = mesesSelected.Value.Replace("chk_mes_", "");
        var allAlturaList = GetIds(alturaSelected.Value.Replace("chk_altura_", ""), '|');
        StringBuilder sbAlt = new StringBuilder();
        for (int i = 0; i < allAlturaList.Count(); i++)
        {

            sbAlt.Append("|" + AlturasList[allAlturaList[i]].min.ToString() + "//" + AlturasList[allAlturaList[i]].max.ToString());
        }
        if (sbAlt.ToString().StartsWith("|")) { sbAlt.Remove(0, 1); }
        ApplyFilters("", "", allcategorys, allsubCategorys, allcolors, minp, maxp, allMeses, sbAlt.ToString());

    }
    public void pageNumberClick(object sender, EventArgs e)
    {
        try
        {

        }
        catch (Exception)
        {
            throw;
        }
    }
    protected void drpCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Redirect("~/Categories.aspx?c=" + ((DropDownList)sender).SelectedValue.ToString());
    }
    protected void LoadBanners()
    {
        var banner1 = new ServiceUI().GetBanner(BannerType.Top);
        for (int i = 0; i < banner1.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner1[i].Url, NavigateUrl = banner1[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner1[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel.Controls.Add(c);
            paging.Controls.Add(p);
        }
        var banner2 = new ServiceUI().GetBanner(BannerType.Middle);
        for (int i = 0; i < banner2.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner2[i].Url, NavigateUrl = banner2[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner2[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel2.Controls.Add(c);
            paging2.Controls.Add(p);
        }
        var banner3 = new ServiceUI().GetBanner(BannerType.Bottom);
        for (int i = 0; i < banner3.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner3[i].Url, NavigateUrl = banner3[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner3[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel3.Controls.Add(c);
            paging3.Controls.Add(p);
        }
    }

    public class Altura
    {
        public Int32 min { get; set; }
        public Int32 max { get; set; }
    }
    public readonly List<Altura> AlturasList = new List<Altura>()
        {
            new Altura{ min = 0 ,max = 10},
            new Altura{ min = 10 ,max = 25},
            new Altura{ min =25 ,max = 50},
            new Altura{ min = 50 ,max = 100},
            new Altura{ min = 100 ,max = 150},
            new Altura{ min = 150 ,max = 200},
            new Altura{ min = 200 ,max = 300},
            new Altura{ min = 300 ,max = 99999999}
        };

}